package com.wms.controller;

import com.wms.common.JwtUtils;
import com.wms.common.Result;
import com.wms.entity.User;
import com.wms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j//日志
@RestController//控制器
public class AuthController {

    //用户服务
    private final UserService userService;

    //构造方法注入用户服务
    @Autowired
    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @CrossOrigin//跨域
    @PostMapping({"/login", "/api/login"})//请求路径
    public Result login(@RequestBody User user) {
        log.info("用户登录:{}", user);
        User u = userService.login(user);

        //登录成功
        if(u != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", u.getId());//用户id
            claims.put("no", u.getNo());//用户账号
            claims.put("name", u.getName());//用户名称

            //生成令牌
            String jwt = JwtUtils.generateJwt(claims);
            log.info("下发令牌:{}", jwt);
            return Result.suc(jwt);
        }

        //登录失败,返回失败信息
        return Result.fail();
    }
}